package heven.holt.wan.android.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import heven.holt.library.BR
import heven.holt.wan.android.databinding.ItemArticleBinding
import heven.holt.wan.android.model.ArticleModel

class ArticleHomeAdapter :
    PagingDataAdapter<ArticleModel, ArticleHomeAdapter.ArticleViewHolder>(ArticleComparator()) {

    private var onItemClickListener: ((View, ArticleModel) -> Unit)? = null

    fun setOnItemClickListener(onItemClickListener: (View, ArticleModel) -> Unit) {
        this.onItemClickListener = onItemClickListener
    }

    class ArticleViewHolder(
        val binding: ItemArticleBinding,
        private val onItemClickListener: ((View, ArticleModel) -> Unit)?
    ) : RecyclerView.ViewHolder(binding.root) {
        init {
            binding.root.setOnClickListener {
                onItemClickListener?.invoke(it, binding.article!!)
            }
        }
    }

    override fun onBindViewHolder(holder: ArticleViewHolder, position: Int) {
        val articleModel: ArticleModel = getItem(position)!!
        holder.binding.setVariable(BR.article, articleModel)
        holder.binding.executePendingBindings()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ArticleViewHolder {
        return ArticleViewHolder(
            ItemArticleBinding.inflate(
                LayoutInflater.from(parent.context),
                parent,
                false
            ), onItemClickListener
        )
    }

    class ArticleComparator : DiffUtil.ItemCallback<ArticleModel>() {
        override fun areItemsTheSame(oldItem: ArticleModel, newItem: ArticleModel): Boolean =
            oldItem.id == newItem.id

        override fun areContentsTheSame(oldItem: ArticleModel, newItem: ArticleModel): Boolean =
            oldItem == newItem
    }

}